URL = "http://openpgm.googlecode.com/files/libpgm-%(VERSION)s.tar.gz"
VERSIONS = ["5.1.118"]
DEFAULT_VERSION = "5.1.118"
DEPENDS = ["patch"]
REQUIRES = ["cmake", "perl"]

from source.builders import CMakeBuilder, ConfigureMakeBuilder
import os, ext.patch

class OpenPGMConfigureMakeBuilder(ConfigureMakeBuilder):
  def configure( self ):
    ''' Reset extractedpath '''
    self.extractedpath = self.extractedpath + os.sep + "openpgm" + os.sep + "pgm"
    ConfigureMakeBuilder.configure(self)


class OpenPGMCMakeBuilder(CMakeBuilder):
  def configure( self ):
    self.builddir = self.extractedpath + os.sep + "build" 
    self.sourcedir = self.extractedpath + os.sep + "openpgm" + os.sep + "pgm"

    if not os.path.exists( self.builddir ):
      os.makedirs(self.builddir)

    args = " -DPATCH_EXECUTABLE=%s" % self.dependencies["patch"].getpatchexec()

    os.chdir( self.builddir )
    print self.builddir
    self.setgenerator()

    if self.debug:
      self.execute( "cmake " + self.sourcedir + " " +args+" -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=" + self.installpath()  + " -G\"" + self.generator + "\"")
    else:
      self.execute( "cmake "+ self.sourcedir + " " + args+" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=" + self.installpath()  + " -G\"" + self.generator + "\"")

  def make(self):
    os.chdir( self.builddir )
    print self.builddir
    if self.generator == "Unix Makefiles":
      self.makeUnixMakefiles()
    elif self.generator.startswith("Visual Studio"):
      self.make_general()

  def patch(self):
    #Disable auto linking
    os.chdir(self.extractedpath)
    patchstr = """ 
diff -r 9d3304cf6840 openpgm/pgm/include/pgm/pgm.h
--- openpgm/pgm/include/pgm/pgm.h	Mon Oct 15 14:07:52 2012 +0200
+++ openpgm/pgm/include/pgm/pgm.h	Mon Oct 15 14:08:42 2012 +0200
@@ -27,7 +27,7 @@
 
 #ifdef _MSC_VER
 /* library dependencies for Visual Studio application builds */
-#	pragma comment (lib, "libpgm")
+//#	pragma comment (lib, "libpgm")
 #	pragma comment (lib, "ws2_32")
 #	pragma comment (lib, "iphlpapi")
 #	pragma comment (lib, "winmm")
"""
    p = ext.patch.fromstring(patchstr)
    print "Patch applied: ", p.apply()


def decider( machine, dirs ):
  return { "Linux" : OpenPGMConfigureMakeBuilder,
           "Windows" : OpenPGMCMakeBuilder }[machine.platform]

BUILDER = decider
